<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.menuName" class="list-input" placeholder="搜索菜单名称" @input="handleSearchInput"
               @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.menuName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">菜单类型</text>
            <BottomSelect v-model="queryParams.menuType" :options="menuTypeOptions" value-field="value"
                          label-field="text" placeholder="请选择菜单类型" title="选择菜单类型"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">状态</text>
            <BottomSelect v-model="queryParams.status" :options="statusOptions" value-field="value" label-field="text"
                          placeholder="请选择状态" title="选择状态"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">是否可见</text>
            <BottomSelect v-model="queryParams.visible" :options="visibleOptions" value-field="value" label-field="text"
                          placeholder="请选择可见性" title="选择可见性"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">权限字符</text>
            <uni-easyinput v-model="queryParams.perms" placeholder="请输入权限字符" :clearable="true"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:menu:add'])">
        <uni-icons type="plus" size="14" color="#007aff"/>
        <text>新增</text>
      </view>
      <view class="btn btn-default" @click="toggleExpandAll">
        <uni-icons :type="expandAll ? 'minus' : 'plus'" size="14" color="#666"/>
        <text>{{ expandAll ? '折叠' : '展开' }}</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 菜单树形列表 -->
    <view class="list-content">
      <view v-for="menu in flatMenuList" :key="menu.menuId" class="list-item" :class="`level-${menu.level}`"
            :style="{ paddingLeft: (menu.level * 20) + 'px' }" @click="handleView(menu)">
        <view class="list-avatar">
          <uni-icons :type="getMenuIcon(menu.menuType)" size="24" :color="getMenuIconColor(menu.menuType)"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <view class="title-with-expand">
              <view class="expand-icon" v-if="menu.children && menu.children.length > 0"
                    @click.stop="toggleMenuExpand(menu)">
                <uni-icons :type="menu.expanded ? 'minus' : 'plus'" size="18" color="#666"></uni-icons>
              </view>
              <text class="list-title">{{ menu.menuName }}</text>
            </view>
            <text class="list-subtitle" v-if="menu.perms">权限: {{ menu.perms }}</text>
            <view class="status-badge" :class="getMenuStatusClass(menu)">{{ getMenuStatusText(menu) }}</view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">ID：{{ menu.menuId }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="flag" size="14" color="#999"/>
              <text class="detail-text">{{ getMenuTypeText(menu.menuType) }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="up-down" size="14" color="#999"/>
              <text class="detail-text">排序：{{ menu.orderNum }}</text>
            </view>
            <view class="detail-item" v-if="menu.path">
              <uni-icons type="navigate" size="14" color="#999"/>
              <text class="detail-text">{{ menu.path }}</text>
            </view>
            <view class="detail-item" v-if="menu.component">
              <uni-icons type="gear" size="14" color="#999"/>
              <text class="detail-text">{{ menu.component }}</text>
            </view>
            <view class="detail-item" v-if="menu.appIcon && menu.menuType === 'C'">
              <uni-icons :type="menu.appIcon" size="14" :color="menu.appColor || '#409EFF'"/>
              <text class="detail-text">APP图标：{{ menu.appIcon }}</text>
            </view>
            <view class="detail-item" v-if="menu.appColor && menu.menuType === 'C'">
              <view class="color-preview" :style="{ backgroundColor: menu.appColor }"></view>
              <text class="detail-text">APP颜色：{{ menu.appColor }}</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleUpdate(menu)"
                v-if="checkPermission(['system:menu:edit'])">
            <uni-icons type="compose" size="14" color="#007aff"/>
            <text class="action-text">编辑</text>
          </view>
          <view class="action-btn action-success" @click.stop="handleAddChild(menu)"
                v-if="checkPermission(['system:menu:add'])">
            <uni-icons type="plus" size="14" color="#34c759"/>
            <text class="action-text">新增</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(menu)"
                v-if="checkPermission(['system:menu:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"/>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="!loading && menuList.length === 0" class="list-empty">
      <uni-icons type="list" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无菜单数据</text>
      <button class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:menu:add'])">添加菜单</button>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {delMenu, listMenu} from '@/api/system/menu'
import {handleTree} from '@/utils/ruoyi'

import {usePermission} from '@/utils/permission'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()
const checkPermission = usePermission()

// 数据定义
const menuList = ref([])
const total = ref(0)
const loading = ref(false)
const expandAll = ref(false)
const filterPopup = ref(null)
const expandTrigger = ref(0) // 用于触发展开状态变化
let searchTimer = null

// 计算属性 - 扁平化的菜单列表用于渲染
const flatMenuList = computed(() => {
  // 依赖 expandTrigger 来触发重新计算
  expandTrigger.value
  return flattenMenuTree(menuList.value)
})

// 查询参数
const queryParams = reactive({
  menuName: '',
  menuType: '',
  status: '',
  visible: '',
  perms: ''
})

// 选项数据
const menuTypeOptions = [
  {value: '', text: '全部类型'},
  {value: 'M', text: '目录'},
  {value: 'C', text: '菜单'},
  {value: 'F', text: '按钮'}
]

const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
]

const visibleOptions = [
  {value: '', text: '全部'},
  {value: '0', text: '显示'},
  {value: '1', text: '隐藏'}
]

// 页面加载
onMounted(() => {
  getList()
})

// 获取菜单列表
async function getList() {
  loading.value = true

  try {
    const response = await listMenu(queryParams)
    if (response.code === 200) {
      const menuData = response.data || []
      const treeData = handleTree(menuData, 'menuId', 'parentId')
      // 初始化展开状态
      menuList.value = initExpandState(treeData)
      total.value = menuData.length
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    proxy.$modal.showToast('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

// 筛选相关函数
function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {menuName: '', menuType: '', status: '', visible: '', perms: ''})
}

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.menuName = '';
  handleQuery()
}

// 查询
function handleQuery() {
  getList()
}

// 树形展开相关函数
function toggleExpandAll() {
  expandAll.value = !expandAll.value
  // 更新所有菜单的展开状态
  updateAllExpandState(menuList.value, expandAll.value)
  // 触发重新计算
  expandTrigger.value++
}


// 初始化展开状态
function initExpandState(menuList, level = 0) {
  return menuList.map(menu => {
    menu.expanded = expandAll.value
    menu.level = level
    if (menu.children && menu.children.length > 0) {
      menu.children = initExpandState(menu.children, level + 1)
    }
    return menu
  })
}

// 更新所有展开状态
function updateAllExpandState(menuList, expanded) {
  menuList.forEach(menu => {
    menu.expanded = expanded
    if (menu.children && menu.children.length > 0) {
      updateAllExpandState(menu.children, expanded)
    }
  })
}

// 切换单个菜单展开状态
function toggleMenuExpand(menu) {
  menu.expanded = !menu.expanded
  // 触发重新计算
  expandTrigger.value++
}

// 扁平化菜单树
function flattenMenuTree(menuList, level = 0) {
  const result = []

  menuList.forEach(menu => {
    menu.level = level
    result.push(menu)

    // 修复展开逻辑：当全局展开或者单个菜单展开时才显示子菜单
    if (menu.children && menu.children.length > 0) {
      const shouldExpand = expandAll.value || menu.expanded
      if (shouldExpand) {
        result.push(...flattenMenuTree(menu.children, level + 1))
      }
    }
  })

  return result
}

// 获取菜单类型文本
function getMenuTypeText(menuType) {
  switch (menuType) {
    case 'M':
      return '目录'
    case 'C':
      return '菜单'
    case 'F':
      return '按钮'
    default:
      return '未知'
  }
}

// 获取菜单状态样式类
function getMenuStatusClass(menu) {
  if (menu.status === '1') return 'status-disabled'
  if (menu.visible === '1') return 'status-warning'
  return 'status-normal'
}

// 获取菜单状态文本
function getMenuStatusText(menu) {
  if (menu.status === '1') return '停用'
  if (menu.visible === '1') return '隐藏'
  return '正常'
}

// 操作处理
function handleAction(action) {
  switch (action.key) {
    case 'add':
      handleAdd()
      break
    case 'refresh':
      handleRefresh()
      break
    case 'expandToggle':
      toggleExpandAll()
      break
  }
}

// 刷新
function handleRefresh() {
  getList()
  proxy.$modal.showToast('刷新成功')
}


// 新增菜单
function handleAdd() {
  uni.navigateTo({
    url: '/pages_system/menu/edit?mode=add'
  })
}

// 查看菜单详情
function handleView(menu) {
  uni.navigateTo({
    url: `/pages_system/menu/edit?mode=view&menuId=${menu.menuId}`
  })
}

// 编辑菜单
function handleUpdate(menu) {
  uni.navigateTo({
    url: `/pages_system/menu/edit?mode=edit&menuId=${menu.menuId}`
  })
}

// 新增子菜单
function handleAddChild(menu) {
  uni.navigateTo({
    url: `/pages_system/menu/edit?mode=add&parentId=${menu.menuId}`
  })
}

// 删除菜单
async function handleDelete(menu) {
  if (menu.children && menu.children.length > 0) {
    proxy.$modal.showToast('存在子菜单，不允许删除')
    return
  }

  const result = await proxy.$modal.confirm(`确认要删除菜单"${menu.menuName}"吗？此操作不可恢复！`)

  if (result) {
    try {
      const response = await delMenu(menu.menuId)

      if (response.code === 200) {
        proxy.$modal.showToast('删除成功')
        getList()
      } else {
        proxy.$modal.showToast(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除菜单失败:', error)
      proxy.$modal.showToast('删除失败')
    }
  }
}

// 获取菜单图标
function getMenuIcon(menuType) {
  switch (menuType) {
    case 'M':
      return 'folder-open'  // 目录使用文件夹图标
    case 'C':
      return 'list'         // 菜单使用列表图标
    case 'F':
      return 'gear'         // 按钮使用齿轮图标
    default:
      return 'list'
  }
}

// 获取菜单图标颜色
function getMenuIconColor(menuType) {
  switch (menuType) {
    case 'M':
      return '#1890ff'      // 目录：蓝色
    case 'C':
      return '#52c41a'      // 菜单：绿色
    case 'F':
      return '#faad14'      // 按钮：橙色
    default:
      return '#1890ff'
  }
}

</script>
<style lang="scss" scoped>
@import '@/styles/tree-page.scss';

.color-preview {
  width: 14px;
  height: 14px;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  display: inline-block;
  margin-right: 4px;
}
</style>